// pages/main/main.js
var crc16util = require("../../utils/crc16util.js");
var startAddr = 0;
var endAddr = 0x10000;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    menu: [{
        img: "/images/ic_ble.png",
        name: "蓝牙调试",
        url: "../selble/selble"
      },
      // {
      //   img:"/images/ic_number.png",
      //   name:"数字转换",
      //   url:"../numberturn/numberturn"
      // },
      // {
      //   img:"/images/ic_time.png",
      //   name:"时间戳转换",
      //   url:"../timeturn/timeturn"
      // },
      // {
      //   img:"/images/ic_code.png",
      //   name:"进制转换",
      //   url:"../codeturn/codeturn"
      // },
      // {
      //   img:"/images/ic_lock.png",
      //   name:"MD5加密",
      //   url:"../MD5/MD5"
      // },
      {
         img:"/images/id_edit.png",
         name:"上传文件",
         url:"upload"
      },
      {
        img: "/images/ic_lock.png",
        name: "crc16",
        url: "../crc16/crc16"
      },
      {
         img:"/images/ic_aboutus.png",
         name:"关于",
         url:"../aboutus/aboutus"
      },
    ],
    reading: 0,
    addr2Read: 0,
    percent: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  doOpenMenu: function (res) {
    var item = res.currentTarget.dataset.item;
    if (!item.url) {
      wx.showModal({
        showCancel: false,
        content: "开发中",
        confirmText: "我知道了"
      })
      return;
    }
    if (item.url == "upload") {
      this.doUpload()
    //} if (item.url == "../aboutus/aboutus") {
    //  this.doTest()
    } else {
      wx.navigateTo({
        url: item.url,
      })
    }
  },

  doUpload: function (res) {
    wx.chooseImage({
      success: function(res) {
        const tempFilePaths = res.tempFilePaths
        wx.saveFile({
          tempFilePath: tempFilePaths[0],
          success (res) {
            const savedFilePath = res.savedFilePath
            const fname = savedFilePath.split('/')
                // tempFilePath可以作为img标签的src属性显示图片
            wx.cloud.uploadFile({
              // 指定上传到的云路径
              cloudPath: fname[fname.length - 1],
              // 指定要上传的文件的小程序临时文件路径
              filePath: savedFilePath,
              // 成功回调
              success: res => {
                console.log('上传成功', res)
                wx.showModal({
                  title: '上传成功',
                  content: res.errMsg,
                  showCancel: false,
                  confirmText: "我知道了"
                })
              },
              fail: res => {
                console.log('上传失败', res)
                wx.showModal({
                  title: '上传失败',
                  content: res.errMsg,
                  showCancel: false,
                  confirmText: "我知道了"
                })
              }
            })
          }
        })
      }
    })
  },

  doTest: function (res) {
    this.data.reading = 1;
    this.data.addr2Read = 0;
    this.doReadData()
    var that = this
    var timerpro = setInterval(() => {
      var x = that.data.addr2Read * 100 / (endAddr - startAddr)
      that.data.percent = Math.round(x*100)/100
      that.setData({
        percent: that.data.percent,
      })
      if(that.data.addr2Read >= endAddr) {
        clearInterval(timerpro)
      }
    }, 1000)
  },
  doReadData: function (res) {
    var cmdH = 0x53
    var cmdL = 0xfefe
    var cmdLen = 0x0e
    var mode = 0x02
    var len2Read = 64
    /* format command */
    let buffer = new ArrayBuffer(cmdLen)

    let dataView = new DataView(buffer)
    dataView.setUint16(0, cmdH, false)
    dataView.setUint16(2, cmdL, false)
    dataView.setUint16(4, cmdLen, false)
    dataView.setUint8(6, mode)
    dataView.setUint32(7, this.data.addr2Read, true)
    dataView.setUint8(11, len2Read)

    var crc = crc16util.CRC.ToCRC16(buffer.slice(0, -2))
    dataView.setUint16(cmdLen - 2, crc, true)
    //app.globalData.bleUtil.sendMsg(buffer);
    console.log(buf2hexStr(buffer))

    if (this.data.addr2Read % 0x400 == 0) {
      console.log('.')
    }
    this.data.reading++
    this.data.addr2Read += 64

    if (this.data.addr2Read < endAddr) {
      setTimeout(() => {
        this.doReadData()
      }, 100)
    }
  }
})


function buf2hexStr(buffer) { // buffer is an ArrayBuffer
  return [...new Uint8Array(buffer)].map(x => x.toString(16).padStart(2, '0')).join('');
}

